/* File: graycode.c
 * --------------------
 * Author: Albin Olausson & Stella Wallin
 * Last modified: 2014-04-15
 * Task: A recursive function that creates
 * graycode for a number of bits selected by
 * the user.
 */

#include <stdio.h>
#include "simpio.h"
#include "strlib.h"

/* Prototypes */

void printGrayCode(int nBits);
void getList1(string list, int nBits);
void getList2(string list, int nBits);

/*Main program */

main(){
	int nBits;

	printf("Program by S. Wallin & A. Olausson.\n\n");
	printf("Number of bits: ");
    nBits = GetInteger();
	printGrayCode(nBits);
}

/*
 * Function: printfGrayCode
 * Usage: printGrayCode(nBits);
 * ----------------------
 * A wrapper function that creates an
 * empty list.
 */

void printGrayCode(int nBits){
	string list = "";

	getList1(list, nBits);
}

/*
 * Function: getList1
 * Usage: getList1(list, nBits);
 * ----------------------
 * This function creates the first half 
 * of the graycode and prints it on the way up
 */

void getList1(string list, int nBits){

	if (nBits == 0)
		printf("%s\n",list);
	else{
		getList1(Concat(list, "0"), nBits-1);
		getList2(Concat(list, "1"), nBits-1);
	}
}

/*
 * Function: getList2
 * Usage: getList2(list, nBits);
 * ----------------------
 * This function creates the second half 
 * of the graycode and prints it on the way up
 */

void getList2(string list, int nBits){
	if(nBits== 0)
		printf("%s\n",list);
	else{
		getList1(Concat(list, "1"), nBits-1);
		getList2(Concat(list, "0"), nBits-1);
	}
}

